//
//  WYCAccount.m
//  WYCweibo
//
//  Created by 魏云超 on 15/11/21.
//  Copyright © 2015年 魏云超. All rights reserved.
//

#import "WYCAccount.h"

@implementation WYCAccount
+(instancetype)accountWithDict:(NSDictionary *)dict
{
    WYCAccount *account = [[self alloc]init];
    account.access_token = dict[@"access_token"];
    account.expires_in = dict[@"expires_in"];
    account.remind_in = dict[@"remind_in"];
    account.uid = dict[@"uid"];
    //1.获取当前时间
    NSDate *now = [NSDate date];
    //2当前时间+过期时间秒数
    account.expires_time = [now dateByAddingTimeInterval:[account.expires_in doubleValue]];
    return account;
}
//归档
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.access_token forKey:@"access_token"];
    [aCoder encodeObject:self.expires_in forKey:@"expires_in"];
    [aCoder encodeObject:self.remind_in forKey:@"remind_in"];
    [aCoder encodeObject:self.uid forKey:@"uid"];
    [aCoder encodeObject:self.expires_time forKey:@"expires_time"];
    [aCoder encodeObject:self.profile_image_url forKey:@"profile_image_url"];
}
//解档
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if ([super init]) {
        self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
        self.expires_in = [aDecoder decodeObjectForKey:@"expires_in"];
        self.remind_in = [aDecoder decodeObjectForKey:@"remind_in"];
        self.uid = [aDecoder decodeObjectForKey:@"uid"];
        self.expires_time = [aDecoder decodeObjectForKey:@"expires_time"];
        self.profile_image_url = [aDecoder decodeObjectForKey:@"profile_image_url"];
    }
    return self;
}
//保存授权模型
-(BOOL)save
{
    //获取存储路径
    NSString *filepath =  [@"account.data" appendDocumentDir];
    //存储数据
   return  [NSKeyedArchiver archiveRootObject:self toFile:filepath];
}
//读取授权模型
+(instancetype)accountFromSandbox
{
    //获取沙盒路径
    NSString *filepath =[@"account.data" appendDocumentDir];
    //解档
    //判断是否过期
    WYCAccount *account =[NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
    NSDate *now = [NSDate date];
    if ([now compare:account.expires_time] != NSOrderedAscending) {
        return nil;
    }
   return  [NSKeyedUnarchiver unarchiveObjectWithFile:filepath];
}
@end
